<?php
/**
 * 后台用户类文件
 * 用户管理 & 用户组管理
 * @package admin
 * @author RD
 */

class AdminUser {
    /**
     * 数据库实例
     * @var Db
     */
    private $_db;
    
    
    /**
     * 构造方法，初始化数据库对象
     * @param db 数据库对象
     * @author RD
     */
    function __construct ($db) {
    
        $this->_db = $db;
    
    }
    
    
    /**
     * 添加管理员帐号
     * @param Array param 关联数组
     * @return affected_rows
     */
    function addAdminUser (Array $param) {
        $newparam = Array ('username'          => trim($param ['username']),
                           'password'      => $this->_encrypt (trim($param ['password'])),
                           'gid'	=> (int)$param['gid']
                          );
        return $this->_db->insert ('admin', $newparam, 1);
    }


    /**
     * 修改管理用户的密码
     * @param Int id 管理用户id
     * @param String newpassword 新密码
     * @return affected_rows
     */
    function changeAdminUserPassword ($id, $newpassword) {
        $where = $this->_db->quoteInto ('id=?', array (intval($id)));
        return $this->_db->update ('admin',
                                  Array('password' => $this->_encrypt (trim($newpassword))),
                                  $where);
    }
    
    
    /**
     * 删除用户
     * @param Int id 用户的id
     * @return affected_rows
     */
    function delAdminUser ($id) {
        $where = $this->_db->quoteInto ('id=?', array ($id));
        if ($this->_db->fetchOne ('select count(*) from admin') == 1)
            return 0;
        return $this->_db->delete ('admin', $where);
    }
    
    
    /**
     * 显示
     * @param Int id 用户的id
     * @return 
     */
    function showAdminUser ($id) {
        return $this->_db->fetchRow ('select * from admin where id=' . intval($id));
    }
    
    /**
     * 分页查看所有的管理用户
     * @param Int nowp 现在是第几页
     * @param Int per_page 每页显示的数量
     * @return Array ('page'=>PageInfo, 'list'=>list)
     */
    function listAdminUser ($where, $nowp = 1, $per_page = 15) {
        $totalNum = $this->_db->fetchOne ('select count(*) from admin ' . $where);
        
        require_once APP . '/application/models/Util.php';
        
        $pageInfo = Util::page ($totalNum, $per_page, $nowp);
        $start    = $pageInfo ['start'];
        $list     = $this->_db->fetchAll ('select * from admin ' . $where .' order by id asc limit ' . $start . ',' . $per_page);
        return Array ('page' => $pageInfo['page'], 'list' => $list);
    }
    
    /**
     * 获取管理员数量
     *
     * @return unknown
     */
    function getUserCount()
    {
    	return $this->_db->fetchOne('select count(*) from admin');
    }
    
    /**
     * 根据用户名和密码判断是否合法
     * @param String name 用户名
     * @param String password 加密处理后的用户密码
     * @return bool 
     */
    function checkAdminUser ($username, $password) {
       $getPassword = $this->_db->fetchOne ('select password from admin where username="' . trim($username) . '"');
       if (empty ($getPassword) || $getPassword != $password)
           return false;
       else
           return true;
    }
     
     
    /**
     * 管理员登陆后台
     * @param String name 用户名
     * @param String password 用户密码,未处理过的
     * @return bool
     */
    function login ($username, $password) {
        if ($this->checkAdminUser (trim($username), $this->_encrypt (trim($password)))) {
            $result = $this->_db->fetchRow ('select * from admin where username="' . $username . '"');
            require_once APP . '/application/models/Util.php';
            $this->_db->update ('admin', Array ('last_login_time' => time(), 'last_login_ip' => Util::getip (true)), 'id=' . $result['id']);
            $_SESSION['ADMIN_ID']               = $result['id'];
            $_SESSION['ADMIN_USERNAME']         = $result['username'];
            $_SESSION['ADMIN_GID']         		= $result['gid'];
            $_SESSION['ADMIN_PASSWORD']         = $result['password'];
            $_SESSION['last_login_time']        = $result['last_login_time'];
            $_SESSION['last_login_ip']          = $result['last_login_ip'];
            return true;
        } else {
            return false;
        }
    }
    
    
    /**
     *判断管理员是否登陆
     * @return bool false 未登陆，true 已登陆
     */
    function checkLogin () {
        if (empty ($_SESSION['ADMIN_ID']) ||
            empty ($_SESSION['ADMIN_USERNAME']) ||
            empty ($_SESSION['ADMIN_PASSWORD']) ||
            !$this->checkAdminUser ($_SESSION['ADMIN_USERNAME'], $_SESSION['ADMIN_PASSWORD'])
            ) {
            return false;
        } else {
            return true;
        }
    }
    
    
    /**
     * 用户退出登陆
     */
    public static function loginOut () {
        unset($_SESSION['ADMIN_ID'],
              $_SESSION['ADMIN_USERNAME'],
              $_SESSION['ADMIN_PASSWORD']);
    }
    
    
    /**
     * 获取登陆信息
     * @return Array (auid=>,name=>, password=> privilege=>)
     */
    public static function getLoginInfo () {
        return Array ('id'                  => empty ($_SESSION['ADMIN_ID'])?'':$_SESSION['ADMIN_ID'],
                      'username'            => empty ($_SESSION['ADMIN_USERNAME'])?'':$_SESSION['ADMIN_USERNAME'],
                      'gid'					=> !isset($_SESSION['ADMIN_GID'])?'':$_SESSION['ADMIN_GID'],
                      'password'            => empty ($_SESSION['ADMIN_PASSWORD'])?'':$_SESSION['ADMIN_PASSWORD'],
                      'last_login_time'     => empty ($_SESSION['last_login_time'])?'':$_SESSION['last_login_time'],
                      'last_login_ip'       => empty ($_SESSION['last_login_ip'])?'':$_SESSION['last_login_ip'],
                      );
    }
    
    
    /**
     * 加密密码,单向加密,所有涉及到用户密码均用这个处理
     * @param String str 被加密的字符串
     * @return String 加密过的字符串
     */
    private function _encrypt ($str) {
        return md5(md5($str));
    }
}